package cn.turboinfo.dongying.api.domain.admin.usecase.activity;

import cn.turboinfo.dongying.api.domain.common.service.activity.ActivityApplyService;
import cn.turboinfo.dongying.api.domain.common.service.activity.ActivityService;
import cn.turboinfo.dongying.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.dongying.api.entity.common.enumeration.user.UserType;
import cn.turboinfo.dongying.api.entity.common.pojo.activity.Activity;
import cn.turboinfo.dongying.api.entity.common.pojo.activity.ActivityApply;
import com.alibaba.excel.EasyExcel;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Component
public class ActivityExportExcelUseCase extends AbstractUseCase<ActivityExportExcelUseCase.InputData, ActivityExportExcelUseCase.OutputData> {
    private final ActivityService activityService;

    private final ActivityApplyService activityApplyService;

    @Override
    protected OutputData doAction(InputData inputData) {

        Long activityId = inputData.getActivityId();
        Activity activity = activityService.getByIdEnsure(activityId);
        List<ActivityApply> activityApplyList = activityApplyService.findByActivityId(activityId)
                .stream()
                .peek(it -> it.setUserTypeName(UserType.get(it.getUserType().getValue()).getName()))
                .toList();

        HttpServletResponse response = inputData.getResponse();

        try {
            response.setContentType("application/vnd.ms-excel");
//            response.setHeader("content-Type", "application/octet-stream");
//            response.setHeader("content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(activity.getName() + ".xlsx", StandardCharsets.UTF_8));
            EasyExcel.write(response.getOutputStream(), ActivityApply.class)
                    .sheet(activity.getName())
                    .doWrite(activityApplyList);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return OutputData.builder()
                .build();
    }

    @EqualsAndHashCode(callSuper = true)
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class InputData extends AbstractUseCase.InputData {
        @NotNull(
                message = "编码不能为空"
        )
        private Long activityId;

        @NotNull
        private HttpServletResponse response;
    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {

    }
}
